<template>
  <div class="file-manager">
    <div class="toolbar">
      <el-button type="primary" @click="handleDownloadAll">下载全部文件</el-button>
    </div>

    <el-table
        :data="files"
        style="width: 100%"
        stripe
        border
        highlight-current-row
    >
      <el-table-column prop="name" label="文件名" min-width="180">
        <template #default="{ row }">
          <span class="file-name" @click="handleDownload(row)">
            {{ row.name }}
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="size" label="大小" :formatter="formatSize" width="120"/>

      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          {{ row.type || getFileType(row.name) }}
        </template>
      </el-table-column>

      <el-table-column prop="modified" label="修改时间" :formatter="formatDate" width="180"/>

      <el-table-column label="方向" width="100">
        <template #default="{ row }">
          <el-tag :type="row.direction === '内部' ? 'success' : 'warning'" effect="dark">
            {{ row.direction }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="statusTypeMap[row.status]" effect="light">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <div class="action-buttons">
            <el-tooltip content="下载文件" placement="top">
              <el-button
                  size="small"
                  type="primary"
                  @click="handleDownload(row)"
                  icon="el-icon-download"
                  circle
              />
            </el-tooltip>

            <el-tooltip content="删除文件" placement="top">
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                  icon="el-icon-delete"
                  circle
              />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import {
  ElMessage,
  ElMessageBox,
  ElTag,
  ElButton,
  ElTooltip
} from 'element-plus';

// 硬编码文件数据
const files = ref([
  {
    name: '项目计划书.pdf',
    size: 2457600,
    modified: '2024-03-15T09:30:00',
    url: '/files/project-plan.pdf',
    type: 'application/pdf',
    direction: '内部',
    status: '已同步'
  },
  {
    name: '财务报告.xlsx',
    size: 3670016,
    modified: '2024-03-14T16:45:00',
    url: '/files/finance-report.xlsx',
    direction: '外部',
    status: '待审核'
  },
  {
    name: '产品原型图.png',
    size: 1520435,
    modified: '2024-03-13T11:20:00',
    url: '/images/prototype.png',
    direction: '内部',
    status: '已归档'
  },
  {
    name: '会议纪要.txt',
    size: 12288,
    modified: '2024-03-12T14:15:00',
    url: '/documents/meeting-notes.txt',
    direction: '内部',
    status: '待同步'
  },
  {
    name: '用户手册.docx',
    size: 4194304,
    modified: '2024-03-10T10:00:00',
    url: '/docs/user-manual.docx',
    direction: '外部',
    status: '已过期'
  }
]);

// 状态类型映射
const statusTypeMap = {
  '等待': 'success',
  '待审核': 'warning',
  '已归档': 'info',
  '待同步': 'danger',
  '已过期': 'danger'
};

// 批量下载处理
const handleDownloadAll = () => {
  ElMessageBox.confirm('将下载全部文件（可能会触发多次保存对话框）', '批量下载', {
    confirmButtonText: '继续下载',
    cancelButtonText: '取消'
  }).then(() => {
    files.value.forEach(file => {
      const link = document.createElement('a');
      link.href = file.url;
      link.download = file.name;
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
    ElMessage.success('已开始批量下载');
  }).catch(() => {
  });
};

// 格式化文件大小
const formatSize = (row, column, cellValue) => {
  const size = cellValue || row.size;
  if (size === 0) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB'];
  const exp = Math.floor(Math.log(size) / Math.log(1024));
  return `${(size / Math.pow(1024, exp)).toFixed(2)} ${units[exp]}`;
};

// 格式化日期
const formatDate = (row, column, cellValue) => {
  return new Date(cellValue || row.modified).toLocaleString();
};

// 文件类型识别
const getFileType = (filename) => {
  const ext = filename.split('.').pop().toLowerCase();
  const types = {
    pdf: 'PDF',
    doc: 'Word',
    docx: 'Word',
    xls: 'Excel',
    xlsx: 'Excel',
    jpg: 'JPEG Image',
    png: 'PNG Image',
    txt: 'Text File'
  };
  return types[ext] || 'Unknown';
};

// 文件下载
const handleDownload = (file) => {
  if (!file.url) {
    ElMessage.error('该文件暂无下载地址');
    return;
  }

  const link = document.createElement('a');
  link.href = file.url;
  link.download = file.name;
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 文件删除
const emit = defineEmits(['delete']);
const handleDelete = (file) => {
  ElMessageBox.confirm('确定要删除这个文件吗？', '警告', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    customClass: 'delete-confirm'
  }).then(() => {
    emit('delete', file);
  }).catch(() => {
  });
};
</script>

<style scoped>
.file-manager {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.file-name {
  color: #409EFF;
  cursor: pointer;
  transition: all 0.3s;
}

.file-name:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table .cell) {
  padding: 8px 12px;
}

:deep(.delete-confirm) {
  min-width: 320px;
}
</style>
